import {
    _decorator,
    Component,
    EventTouch,
    instantiate,
    NodeEventType,
    Prefab,
    Vec3,
    CCBoolean,
    resources,
    Sprite,
    SpriteFrame
} from 'cc';

const {ccclass, property} = _decorator;

@ccclass('PlayerController')
export class PlayerController extends Component {

    /**
     * 子弹预制体
     */
    @property(Prefab)
    bulletPrefab: Prefab = null;

    /**
     * 已销毁
     */
    @property(CCBoolean)
    destroyed: boolean = false;

    start() {
        console.log("PlayerController...");
        // 手指跟随
        this.node.on(NodeEventType.TOUCH_MOVE, (event: EventTouch) => {
            // 获取触摸坐标
            // Location：(472.00, 802.00)
            // UILocation：(236.99, 402.68)
            // console.log("Location："+event.getLocation());
            // console.log("UILocation："+event.getUILocation());
            this.node.setWorldPosition(new Vec3(event.getUILocation().x, event.getUILocation().y));
        });

        // 生成子弹【自动生成（定时器）】
        this.schedule(() => {
            // 从预制体中创建节点
            let bulletNode = instantiate(this.bulletPrefab);
            // 设置父节点
            bulletNode.setParent(this.node.parent);
            // 设置位置
            bulletNode.setPosition(this.node.position.x, this.node.position.y + 80);
        }, 0.1);
    }

    update(deltaTime: number) {
        // 销毁
        if (this.destroyed) {
            this.node.destroy();
            return;
        }
    }

    /**
     * 销毁
     */
    die() {
        // 未销毁时
        if (!this.destroyed) {
            // 播放死亡动画
            resources.load("hero_die/spriteFrame", SpriteFrame, (err: Error, data: SpriteFrame) => {
                if (!err) {
                    this.node.getComponent(Sprite).spriteFrame = data;
                }
            });
            // 延时销毁
            setTimeout(() => {
                this.destroyed = true;
            }, 200);
        }
    }
}

